
package cn.base.web.authc;

import cn.rengy.auth.Authentication;
import cn.rengy.auth.exception.AuthException;
import cn.rengy.lang.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * 至少要一个允许访问
 */
@Component
@Slf4j
public class AtLeastOneSuccessfulStrategy implements AccessStrategy  {

    @Autowired
    private List<AccessControl> accessControls;
    @Override
    public ResultEntity<HttpStatus, Authentication> isAccessAllowed(Object request, Object response) {
        ResultEntity<HttpStatus, Authentication> resultEntity=null;
        for (AccessControl control : accessControls) {
            try{
                resultEntity=control.isAccessAllowed(request,response);
                if(Boolean.TRUE.equals(resultEntity.isSuccess())){
                    break;
                }else{
                    log.debug("Skipping control, [{}] does not support request .", control.getClass().getName());
                }
            }catch (AuthException e){
                log.info("[{}] auth error [{}],Ignore,Next.", control.getClass().getName(),e.getMessage());
            }
        }
        if(resultEntity==null||!resultEntity.isSuccess()){
            log.debug("All AccessControl auth fail.");
            resultEntity=ResultEntity.fail(HttpStatus.UNAUTHORIZED,"All AccessControl auth fail.");
        }
        return resultEntity;
    }


}
